package com.hyg.lib_music.ui.activity;


import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Parcelable;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.Base.BaseApplication;
import com.hyg.lib_common.DataModel.EventBusMessage;
import com.hyg.lib_common.DataModel.Music.Music;
import com.hyg.lib_common.DataUtil.UserSPUtils;
import com.hyg.lib_common.constant.Constants;
import com.hyg.lib_common.ui.activity.BlueToothListActivity;
import com.hyg.lib_music.R;
import com.hyg.lib_music.databinding.ActivityMusicMainBinding;
import com.hyg.lib_music.service.MusicService;
import com.hyg.lib_music.ui.fragment.KnowledgeSort1Fragment;
import com.hyg.lib_music.ui.fragment.KnowledgeSort2Fragment;
import com.hyg.lib_music.ui.fragment.KnowledgeSort3Fragment;
import com.hyg.lib_music.ui.fragment.MusicCategoryListFragment;
import com.hyg.lib_music.ui.fragment.MusicFavListFragment;
import com.hyg.lib_music.ui.fragment.MusicRecommendFragment;
import com.hyg.lib_music.ui.fragment.RecommendYangshengFragment;
import com.hyg.lib_music.util.MusicFavManager;

import org.greenrobot.eventbus.Subscribe;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Route(path = Constants.PATH_ACTIVITY_MODULE_HEALTH_MUSICBED)
public class MusicMainActivity extends BaseActivity {
    ActivityMusicMainBinding binding;
    MusicRecommendFragment recommendFragment;
    MusicCategoryListFragment categoryListFragment;
    MusicFavListFragment favListFragment;
    FragmentManager fragmentManager;
    Fragment currrentFrg;
    public static MusicService.MusicServiceBinder serviceBinder;
    public static String result_type = "";
    public static int music_image_path = R.mipmap.yangsheng_music_icon;
    Intent serviceIntent;
    Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//       if(savedInstanceState!= null){
//    String FRAGMENTS_TAG ="android:support:fragments";
//savedInstanceState.remove(FRAGMENTS_TAG);
//       }


        binding = ActivityMusicMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        init();
    }


    @Override
    public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) {
//        super.onSaveInstanceState(outState, outPersistentState);
    }

    public void init() {
        StatusBarUtil.setStatusBar(1, this, getResources().getColor(R.color.white), 60, null, null, true);
        showMusciRecommend();
        initListener();
        binding.rbtnLiaoyu.performClick();
        initPlayService();
    }

    public void showMusciRecommend() {
        fragmentManager = getSupportFragmentManager();
        recommendFragment = new MusicRecommendFragment();
        categoryListFragment = new MusicCategoryListFragment();
        favListFragment = new MusicFavListFragment();
        switchFragment(recommendFragment);
    }


    private void switchFragment(Fragment fragment) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        if (currrentFrg == null) {
            transaction.add(R.id.ln_fragment_container, fragment).commit();
            currrentFrg = fragment;
        } else if (fragment != currrentFrg) {
            if (!fragment.isAdded()) {
                transaction.hide(currrentFrg)
                        .add(R.id.ln_fragment_container, fragment).commit();
            } else {
                transaction.hide(currrentFrg)
                        .show(fragment).commit();
            }
            currrentFrg = fragment;
        }
    }

    public void initListener() {
        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        binding.musicBluetooth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkBlueToothList();
            }
        });
        binding.rbtnLiaoyu.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) switchFragment(recommendFragment);
            }
        });
        binding.rbtnYueku.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) switchFragment(categoryListFragment);
            }
        });
        binding.rbtnXihuan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) switchFragment(favListFragment);
            }
        });
        binding.viewMusicPlayController.ivMusicPlayControl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (serviceBinder != null) {
                    serviceBinder.playOrPause();
                }
            }
        });
        binding.viewMusicPlayController.rootPlayController.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MusicMainActivity.this,
                        MusicPlayingDetailActivity.class);
                intent.putExtra("test_result", result_type);
                Log.i("lgb", "onClick: test_result=" + result_type);
                startActivity(intent);
                overridePendingTransition(R.anim.in_from_down, R.anim.hold);
            }
        });
        binding.viewMusicPlayController.ivMusicMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Music> playList=serviceBinder.getPlayingList();
                Intent intent = new Intent(MusicMainActivity.this,
                        PlayingListActivity.class);
                intent.putParcelableArrayListExtra("data", (ArrayList<? extends Parcelable>)playList);
                Log.i("lgb", "onClick: test_result=" + result_type);
                startActivity(intent);
                overridePendingTransition(R.anim.in_from_down, R.anim.hold);
            }
        });
    }

    public void updataMusicIcon(int id) {
        Glide.with(MusicMainActivity.this).load(id).into(binding.viewMusicPlayController.ivMusicImage);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (serviceBinder != null)
            Glide.with(MusicMainActivity.this).load(serviceBinder.getImagePath()).into(binding.viewMusicPlayController.ivMusicImage);
    }

    public void initPlayService() {
        serviceIntent = new Intent(this, MusicService.class);
        startService(serviceIntent);
        bindService(serviceIntent, mServiceConnection, BIND_AUTO_CREATE);
    }

    //定义与服务的连接的匿名类
    private ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //绑定成功后，取得MusicSercice提供的接口
            serviceBinder = (MusicService.MusicServiceBinder) service;
            //注册监听器
            serviceBinder.registerOnStateChangeListener(listenr);
            //获得当前音乐
            Music item = serviceBinder.getCurrentMusic();

//            Log.i("lgb", "onServiceConnected: "+item.toString());
            if (item == null) {
                binding.viewMusicPlayController.rootPlayController.setVisibility(View.GONE);
                return;
            } else {
                binding.viewMusicPlayController.rootPlayController.setVisibility(View.VISIBLE);
            }
            if (serviceBinder.isPlaying()) {

                if (recommendFragment != null) {
                    recommendFragment.startCount();
                }
                Glide.with(MusicMainActivity.this).load(serviceBinder.getImagePath()).into(binding.viewMusicPlayController.ivMusicImage);
                //如果正在播放音乐, 更新信息
                binding.viewMusicPlayController.tvMusicName.setText(item.musicName);
//                String logoUrl = MusicFavManager.sharedManager().getLogoUrl(item.cateId);
//                if (logoUrl != null && !logoUrl.isEmpty()) {
//                    Glide.with(BaseApplication.getInstance()).load(logoUrl).error(R.mipmap.headimg).into(binding.viewMusicPlayController.ivMusicImage);
//                }
                binding.viewMusicPlayController.ivMusicPlayControl.setImageResource(R.mipmap.new_play_controler_pause);
            } else {
                //当前有可播放音乐但没有播放
                binding.viewMusicPlayController.tvMusicName.setText(item.musicName);
                binding.viewMusicPlayController.ivMusicPlayControl.setImageResource(R.mipmap.new_music_play_btn);
                Glide.with(MusicMainActivity.this).load(serviceBinder.getImagePath()).into(binding.viewMusicPlayController.ivMusicImage);
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            //断开连接之后, 注销监听器
            serviceBinder.unregisterOnStateChangeListener(listenr);
        }
    };


    //实现监听器监听MusicService的变化，
    private MusicService.OnStateChangeListenr listenr = new MusicService.OnStateChangeListenr() {
        @Override
        public void onPlayProgressChange(long played, long duration) {

        }

        @Override
        public void onPlay(final Music item) {
            Log.i("lgb", "onPlay: ");
            recommendFragment.startCount();

            if (binding.viewMusicPlayController.rootPlayController.getVisibility() != View.VISIBLE) {
                binding.viewMusicPlayController.rootPlayController.setVisibility(View.VISIBLE);
            }
            binding.viewMusicPlayController.tvMusicName.setText(item.musicName);
            binding.viewMusicPlayController.ivMusicPlayControl.setImageResource(R.mipmap.new_play_controler_pause);
            Glide.with(MusicMainActivity.this).load(serviceBinder.getImagePath()).into(binding.viewMusicPlayController.ivMusicImage);
        }

        @Override
        public void onPause() {
            //变为暂停状态时
            recommendFragment.stopCount();
            binding.viewMusicPlayController.ivMusicPlayControl.setImageResource(R.mipmap.new_music_play_btn);
        }
    };

    @Override
    public void finish() {
        super.finish();
        UserSPUtils.clearMusicSetting(this);
        serviceBinder.unregisterOnStateChangeListener(listenr);
        unbindService(mServiceConnection);
        serviceBinder = null;
        stopService(serviceIntent);
    }


    public void checkBlueToothList() {
        Intent intent = new Intent(this, BlueToothListActivity.class);
        intent.putExtra("type", "1");
        startActivity(intent);
    }


    @Subscribe
    public void onEvent(EventBusMessage message) {
        //接收以及处理数据
        if (message.getmessage().contains("time")) {
            int times = Integer.parseInt(message.getmessage().substring(4));
            switch (times) {
                case 0:
                    handler.removeCallbacksAndMessages(null);
                    break;
                case 1:
                    times = 15 * 60 * 1000;
                    break;
                case 2:
                    times = 2 * 15 * 60 * 1000;
                    break;
                case 3:
                    times = 3 * 15 * 60 * 1000;
                    break;
                case 4:
                    times = 4 * 15 * 60 * 1000;
                    break;
            }
            Log.i("lgb", "onEvent: timessssss="+times);
            if (times == 0) {
                handler.removeCallbacksAndMessages(null);
            } else {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (serviceBinder.isPlaying()) {
                            serviceBinder.playOrPause();
                        }
                    }
                }, times);
            }
        }
    }
}